package com.fpt.edu.vn.h2tv.filter;

import java.io.IOException;
import java.net.HttpURLConnection;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fpt.edu.vn.h2tv.common.AppConfiguration;
import com.fpt.edu.vn.h2tv.common.ElementName;
import com.fpt.edu.vn.h2tv.dto.UserInfo;

public class UserAuthenticationFilter implements Filter{

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException,
            ServletException {

        HttpServletRequest request = (HttpServletRequest) arg0;
        
        String authenValue ;
        if( (authenValue = request.getParameter(AppConfiguration.authenKey))!=null){
            if(authenValue.equals(AppConfiguration.authenValue)){
                arg2.doFilter(arg0, arg1);
                return;
            }
        }
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(ElementName.USER_INFO);
        if(userInfo!=null){
            if(userInfo.getRole().equals(ElementName.ADMIN)||userInfo.getRole().equals(ElementName.STAFF)||userInfo.getRole().equals(ElementName.CUSTOMER)){
                //check if admin,staff, of Customer pass
                arg2.doFilter(arg0, arg1);
                return;
            }
        }
        HttpServletResponse response = (HttpServletResponse) arg1;
        response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        
        
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }

}
